<template>
  <div class="alarm-page">
    <div class="header">
      <div class="search-container">
        <el-input
          v-model="searchParams.displayID"
          placeholder="请输入DisplayID精确搜索"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        ></el-input>
        <el-input
          v-model="searchParams.keyword"
          placeholder="请输入关键字搜索"
          class="search-input"
          clearable
          @keyup.enter="handleSearch"
        >
          <!-- <template #append>

          </template> -->
        </el-input>
        <el-button type="primary" @click="handleSearch">
          搜索
        </el-button>
        <el-button 
          type="primary" 
          @click="handleAdd"
          v-if="isAdmin || role === 0"
        >
          新增
        </el-button>
      </div>
      <div class="header-right">
        <el-button 
          type="primary" 
          @click="handleShare"
        >
          <el-icon><Share /></el-icon>
          分享
        </el-button>
      </div>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="alarms"
      border
      stripe
      @sort-change="handleSortChange"
      :default-sort="{ prop: 'id', order: 'ascending' }"
      style="width: 100%; margin-top: 20px;"
    >
      <!-- <el-table-column
        prop="id"
        label="ID"
        width="100"
        sortable
      /> -->
      <el-table-column
        prop="displayID"
        label="displayID"
        width="150"
      >
        <template #default="{ row }">
          <div class="cell-content">{{ row.displayID }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="alarm"
        label="报警名称"
        sortable
      >
        <template #default="{ row }">
          <div class="cell-content">{{ row.alarm }}</div>
        </template>
      </el-table-column>
      
      <el-table-column
        prop="meaning"
        label="描述"
      >
        <template #default="{ row }">
          <div class="cell-content">{{ row.meaning }}</div>
        </template>
      </el-table-column>
      <el-table-column
        prop="measures"
        label="排查方向"
      >
        <template #default="{ row }">
          <div class="cell-content">{{ row.measures }}</div>
        </template>
      </el-table-column>
      <!-- <el-table-column
        prop="remark"
        label="备注"
      >
        <template #default="{ row }">
          <div class="cell-content">{{ row.remark }}</div>
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        width="100"
        fixed="right"
        v-if="isAdmin || role === 0"
      >
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(row)"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="searchParams.page"
        v-model:page-size="searchParams.rows"
        :page-sizes="[5, 10, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 修改弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '修改报警信息' : '新增报警信息'"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="DisplayID" prop="displayID">
          <el-input v-model="form.displayID" type="text" />
        </el-form-item>
        <el-form-item label="报警名称" prop="alarm">
          <el-input v-model="form.alarm" type="text" />
        </el-form-item>
        <el-form-item label="描述" prop="meaning">
          <el-input v-model="form.meaning" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="排查方向" prop="measures">
          <el-input v-model="form.measures" type="textarea" :rows="3" />
        </el-form-item>
        <!-- <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from '../plugins/axios'
import { ElMessage } from 'element-plus'
import { Share } from '@element-plus/icons-vue'

// 搜索参数
const searchParams = ref({
  keyword: '',
  page: 1,
  rows: 5,
  sortColumn: 'id',
  sortWay: 'ASC'
})

const alarms = ref([])
const total = ref(0)
const loading = ref(false)

const dialogVisible = ref(false)
const formRef = ref(null)
const form = ref({
  id: '',
  displayID: '',
  alarm: '',
  meaning: '',
  messsures: '',
  remark: ''
})

// 表单验证规则
const rules = {
  displayID: [{ required: true, message: '请输入DisplayID', trigger: 'blur' }],
  alarm: [{ required: true, message: '请输入报警名称', trigger: 'blur' }],
  meaning: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  messsures: [{ required: true, message: '请输入详情', trigger: 'blur' }]
}

// 添加编辑状态标记
const isEdit = ref(false)

// 重置表单
const resetForm = () => {
  form.value = {
    id: '',
    displayID: '',
    alarm: '',
    meaning: '',
    measures: '',
    remark: ''
  }
}

// 获取报警列表
const fetchAlarms = async () => {
  loading.value = true
  try {
    const response = await axios.post('/alarm/queryByCondition', {
      ...searchParams.value,
      sortColumn: searchParams.value.sortColumn || 'id',  // 确保始终有排序列
      sortWay: searchParams.value.sortWay || 'DESC'       // 确保始终有排序方式
    })
    if (response.data.code === 1) {
      alarms.value = response.data.data
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.data.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取报警列表失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  searchParams.value.page = 1
  fetchAlarms()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  searchParams.value.page = page
  fetchAlarms()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  searchParams.value.rows = size
  searchParams.value.page = 1
  fetchAlarms()
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return time.replace(/\.0$/, '')
}

// 处理新增按钮点击
const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

// 处理编辑按钮点击
const handleEdit = (row) => {
  form.value = {
    id: row.id,
    displayID: row.displayID || '',  // 确保设置 displayID
    alarm: row.alarm,
    meaning: row.meaning,
    measures: row.measures,
    remark: row.remark || ''
  }
  isEdit.value = true
  dialogVisible.value = true
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const url = isEdit.value ? '/alarm/update' : '/alarm/save'
        const response = await axios.post(url, form.value)
        
        if (response.data.code === 1) {
          ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
          dialogVisible.value = false
          fetchAlarms()  // 刷新列表
        } else {
          ElMessage.error(response.data.msg || (isEdit.value ? '修改失败' : '新增失败'))
        }
      } catch (error) {
        console.error(isEdit.value ? '修改失败:' : '新增失败:', error)
        ElMessage.error(isEdit.value ? '修改失败' : '新增失败')
      }
    }
  })
}

// 本地排序方法
const sortData = (data, prop, order) => {
  return [...data].sort((a, b) => {
    if (prop === 'id') {
      // ID 按数字排序
      return order === 'ascending' 
        ? a.id - b.id 
        : b.id - a.id
    } else if (prop === 'alarm') {
      // 报警名称按字母排序
      return order === 'ascending'
        ? a.alarm.localeCompare(b.alarm)
        : b.alarm.localeCompare(a.alarm)
    }
    return 0
  })
}

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  if (!order) {
    // 取消排序时恢复原始数据顺序
    fetchAlarms()
  } else {
    // 本地排序
    alarms.value = sortData(alarms.value, prop, order)
  }
}

// 添加分享处理函数
const handleShare = async () => {
  try {
    const url = window.location.href
    await navigator.clipboard.writeText(url)
    ElMessage.success('链接已复制到剪贴板')
  } catch (err) {
    console.error('Failed to copy:', err)
    ElMessage.error('复制链接失败')
  }
}

const isAdmin = localStorage.getItem('isAdmin') === '1'
const role = Number(localStorage.getItem('role'))

// 组件挂载时获取数据
onMounted(() => {
  fetchAlarms()
})
</script>

<style scoped>
.alarm-page {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-right {
  display: flex;
  align-items: center;
}

.search-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

:deep(.el-table) {
  margin-top: 20px;
}

:deep(.el-table__header-wrapper) {
  background-color: #f5f7fa;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: #fafafa;
}

:deep(.cell-content) {
  white-space: pre-wrap;  /* 保留空格和换行 */
  word-break: break-word;  /* 允许在单词内换行 */
  line-height: 1.5;  /* 行高 */
  padding: 8px 0;  /* 上下间距 */
}

:deep(.el-table__cell) {
  padding: 8px !important;  /* 单元格内边距 */
}

:deep(.dialog-footer) {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
}

:deep(.el-form-item__label) {
  font-weight: bold;
}

:deep(.el-input__inner) {
  font-size: 14px;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}

:deep(.el-icon) {
  margin-right: 5px;
}
</style> 